<template>
  <div class="operation-log-container">
    <h2 class="page-title">操作日志</h2>
    <el-card>
      <div class="toolbar">
        <el-form :inline="true" :model="query" class="filter-form">
          <el-form-item label="操作人">
            <el-input v-model="query.adminName" placeholder="操作人用户名" clearable />
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select v-model="query.operationType" placeholder="全部" clearable style="width: 140px;">
              <el-option label="CREATE" value="CREATE" />
              <el-option label="UPDATE" value="UPDATE" />
              <el-option label="DELETE" value="DELETE" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作模块">
            <el-select v-model="query.operationModule" placeholder="全部" clearable style="width: 160px;">
              <el-option label="user" value="user" />
              <el-option label="product" value="product" />
              <el-option label="post" value="post" />
              <el-option label="order" value="order" />
              <el-option label="comment" value="comment" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">查询</el-button>
            <el-button @click="handleReset" :disabled="loading">重置</el-button>
            <el-button @click="handleExport" :disabled="tableData.length === 0">导出CSV</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="pagedData" border stripe v-loading="loading">
        <el-table-column prop="logId" label="ID" width="90" />
        <el-table-column prop="adminName" label="操作人" min-width="120" />
        <el-table-column prop="operationType" label="类型" width="110">
          <template #default="{ row }">
            <el-tag :type="typeTag(row.operationType)">{{ row.operationType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operationModule" label="模块" width="120" />
        <el-table-column prop="operationDetail" label="详情" min-width="260" show-overflow-tooltip />
        <el-table-column prop="ipAddress" label="IP" width="150" />
        <el-table-column prop="createdAt" label="时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="tableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { adminAPI } from '@/api'

const loading = ref(false)
const query = reactive({
  adminName: '',
  operationType: '',
  operationModule: ''
})

const tableData = ref([])

const pageSize = ref(10)
const currentPage = ref(1)
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})

const typeTag = (type) => {
  if (type === 'CREATE') return 'success'
  if (type === 'UPDATE') return 'warning'
  if (type === 'DELETE') return 'danger'
  return ''
}

const formatDateTime = (val) => {
  if (!val) return ''
  try {
    // 兼容后端返回LocalDateTime或字符串
    const d = typeof val === 'string' ? new Date(val) : new Date(val.year, val.monthValue - 1, val.dayOfMonth, val.hour, val.minute, val.second)
    const pad = (n) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  } catch {
    return String(val)
  }
}

const fetchLogs = async () => {
  loading.value = true
  try {
    const res = await adminAPI.getOperationLogs({
      adminName: query.adminName || undefined,
      operationType: query.operationType || undefined,
      operationModule: query.operationModule || undefined
    })
    tableData.value = Array.isArray(res.data) ? res.data : []
    currentPage.value = 1
  } catch (e) {
    // 已在拦截器提示
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  fetchLogs()
}

const handleReset = () => {
  query.adminName = ''
  query.operationType = ''
  query.operationModule = ''
  fetchLogs()
}

const handleExport = () => {
  const headers = ['ID', '操作人', '类型', '模块', '详情', 'IP', '时间']
  const rows = tableData.value.map(r => [
    r.logId ?? '',
    r.adminName ?? '',
    r.operationType ?? '',
    r.operationModule ?? '',
    (r.operationDetail || '').toString().replace(/\n/g, ' '),
    r.ipAddress ?? '',
    formatDateTime(r.createdAt)
  ])
  const csv = [headers, ...rows].map(r => r.map(field => `"${String(field).replace(/"/g, '""')}"`).join(',')).join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `operation_logs_${Date.now()}.csv`
  link.click()
  URL.revokeObjectURL(url)
  ElMessage.success('已导出CSV')
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

onMounted(() => {
  fetchLogs()
})
</script>

<style scoped>
.operation-log-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 24px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.toolbar {
  margin-bottom: 12px;
}

.filter-form :deep(.el-form-item) {
  margin-right: 12px;
  margin-bottom: 12px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>

